const express = require("express");
const router = express.Router();
const Db = require("../utils/db");
const createSql = require("../utils/Create_SQL");
const path = require('path');
const fs = require('fs');
const { errorCode, successCode, config } = require('../config/config');
const request = require("request");
const utils = require("../utils/utils.js");
const nodemailer = require("nodemailer"); // 引入nodemailer 发送邮件模块

/**
 * @swagger
 * /api/email/getCodeByEmail:
 *    get:
 *      tags:
 *      - 用户相关
 *      summary: 获取验证码
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                email:
 *                  type: string
 *                  description: 接收邮箱
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.get("/getCodeByEmail", async (req, res) => {
    if(!config.isSendEmail){
        return res.json({
            ...errorCode[10015],
            message: "邮箱验证码功能已关闭"
        });
    }
    let query = req.query;
    if (!query.email) {
        return res.json({
            ...errorCode[10003],
        });
    }
    // 验证邮箱格式
    let reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?<!\d)$/;
    if (!reg.test(query.email)) {
        return res.json({
            ...errorCode[10004],
            message: "邮箱格式错误"
        });
    }
    let pass = utils.detectSQL(query.email);
    if(!pass){
        res.status(500);
        return res.json({
            ...errorCode[10020],
        });
    }
    let date = new Date();
    let addzore = (num) =>{
        return num < 10 ? '0' + num : num;
    }
    let time = `${date.getFullYear()}-${addzore(date.getMonth() + 1)}-${addzore(date.getDate())} 00:00:00`

    // 一天只能发送5次
    let sql = createSql.select().from("code_expires")
    .where(`name = '${query.email}'`)
    .and("isExpire = 0")
    .and(`addTime >  + '${time}'`)
    .build();
    let result = await Db.query(sql, res);
    if (result.length >= config.codeMaxNum) {
        return res.json({
            ...errorCode[10018],
            message: "今天发送次数已达上限"
        });
    }
    // 查询验证码是否已经发送
    sql = createSql.select().from("code_expires")
    .where(`name = '${query.email}'`)
    .and("isExpire = 0")
    .and(`addTime >  + '${time}'`).build();
    result = await Db.query(sql, res);
    if (result.length) {
        if (result[0].expires > new Date().getTime()) {
            return res.json({
                ...errorCode[10002],
                message: "验证码已发送,请稍后再试"
            });
        }
    }

    // 生成6位随机验证码
    let code = Math.random().toString().slice(-6);
    sql = createSql.insert('code_expires').value({
        ID : utils.getUuid(),
        name : query.email,
        code : code,
        expires : new Date().getTime() + 1000 * 60 * 2,
        addtime : utils.formatDate(new Date().getTime()),
        isExpire : 0,
        type : query.type || 'web'
    }).end();
    result = await Db.query(sql, res);
    // 创建Nodemailer传输器 SMTP 或者 其他 运输机制
    let transporter = nodemailer.createTransport({
        host: "smtp.qq.com", // 第三方邮箱的主机地址
        port: 587,
        secure: false, // true for 465, false for other ports
        auth: {
            user: "zs.duan@foxmail.com", // 发送方邮箱的账号
            pass: "mobukzbqypzhcddb", // 邮箱授权密码
        },
    });
    // 定义transport对象并发送邮件
    let info = await transporter.sendMail({
        from: '"zsduan的个人博客" <zs.duan@foxmail.com>', // 发送方邮箱的账号
        to: query.email, // 邮箱接受者的账号
        subject: "亲爱的用户你好，欢迎使用zsduan的个人博客", // Subject line
        text: "小段博客欢迎你!", // 文本内容
        html: `[zsduan的个人博客]工作人员不会获取你的验证码,您的验证码是:<b>${code}</b>`, // html 内容, 如果设置了html内容, 将忽略text内容
    });
    return res.json({
        ...successCode[200],
    })
})


module.exports = router;